package com.wangzhixuan.commons.shiro;

import com.wangzhixuan.commons.utils.DateUtils;
import com.wangzhixuan.commons.utils.ShiroUtils;
import com.wangzhixuan.model.AuthUser;
import com.wangzhixuan.model.vo.UserVo;
import com.wangzhixuan.service.IRoleService;
import com.wangzhixuan.service.IUserService;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authc.credential.CredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.cache.CacheManager;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.SimplePrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Calendar;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @description：shiro权限认证
 * @author：zhixuan.wang @date：2015/10/1 14:51
 */
public class ShiroDbRealm extends AuthorizingRealm {
	private static final Logger LOGGER = LogManager.getLogger(ShiroDbRealm.class);

	@Autowired
	private IUserService userService;
	@Autowired
	private IRoleService roleService;

	public ShiroDbRealm(CacheManager cacheManager, CredentialsMatcher matcher) {
		super(cacheManager, matcher);
	}

	/**
	 * Shiro登录认证(原理：用户提交 用户名和密码 --- shiro 封装令牌 ---- realm 通过用户名将密码查询返回 ----
	 * shiro 自动去比较查询出密码和用户输入密码是否一致---- 进行登陆控制 )
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken)
			throws AuthenticationException {
		LOGGER.info("Shiro开始登录认证");
		
		
		
		UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
		UserVo uservo = new UserVo();
		uservo.setLoginName(token.getUsername());
		List<AuthUser> list = userService.selectByLoginName(uservo);
		// 获取IP
		String ip = ShiroUtils.getIp();
		// 账号不存在
		if (list == null || list.isEmpty()) {
			return null;
		}
		AuthUser user = list.get(0);
		// 账号未启用
		if (user.getStatus() == 1) {
			throw new UnknownAccountException("该账号注销，请联系管理员恢复账号！");
		}
		if (user.getStatus() == 3) {

			if (DateUtils.calDaysWithSysDate(user.getUpdateTime()) >= 330) {
				throw new UnknownAccountException("该账号即将被注销，请联系管理员恢复账号！");
			} else {

				throw new UnknownAccountException("该账号已转为休眠账号，请联系管理员恢复账号！");
			}
		}
		if (!user.getUserIp().equals(ip)) {
			throw new UnknownAccountException("该账号只能固定IP登陆IP为:" + user.getUserIp());
		}
		// 记录登录时间
		userService.updateLoginTimeById(user.getId());
		// 读取用户的url和角色
		Map<String, Set<String>> resourceMap = roleService.selectResourceMapByUserId(user.getId());
		Set<String> urls = resourceMap.get("urls");
		Set<String> roles = resourceMap.get("roles");
		ShiroUser shiroUser = new ShiroUser(user.getId(), user.getLoginName(), user.getName(), urls, user.getModpwdTime());
		shiroUser.setRoles(roles);
		// 认证缓存信息
		return new SimpleAuthenticationInfo(shiroUser, user.getPassword().toCharArray(),
				ShiroByteSource.of(user.getSalt()), getName());
	}

	/**
	 * Shiro权限认证
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		ShiroUser shiroUser = (ShiroUser) principals.getPrimaryPrincipal();

		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
		info.setRoles(shiroUser.getRoles());
		info.addStringPermissions(shiroUser.getUrlSet());

		return info;
	}

	@Override
	protected Object getAuthenticationCacheKey(PrincipalCollection principals) {
		ShiroUser shiroUser = (ShiroUser) super.getAvailablePrincipal(principals);
		return shiroUser.toString();
	}

	@Override
	protected Object getAuthorizationCacheKey(PrincipalCollection principals) {
		ShiroUser shiroUser = (ShiroUser) super.getAvailablePrincipal(principals);
		return shiroUser.toString();
	}

	/**
	 * 清除用户缓存
	 * 
	 * @param shiroUser
	 */
	public void removeUserCache(ShiroUser shiroUser) {
		SimplePrincipalCollection principals = new SimplePrincipalCollection();
		principals.add(shiroUser, super.getName());
		super.clearCache(principals);
	}

	/**
	 * 清除用户缓存
	 * 
	 * @param loginName
	 */
	public void removeUserCache(String loginName) {
		removeUserCache(new ShiroUser(loginName));
	}

	/**
	 * 清理缓存权限
	 */
	public void clearCachedAuthorizationInfo() {
		this.clearCachedAuthorizationInfo(SecurityUtils.getSubject().getPrincipals());
	}
}
